// API基础URL
const BASE_URL = 'http://localhost:5000';

// 判断是否是测试环境
const isTestEnvironment = () => {
	// 返回 false 使系统始终使用真实 API
	return false;
};

// 获取存储的token
const getToken = () => {
	return uni.getStorageSync('token') || '';
};

// 通用请求方法
const request = (url, method, data = {}, isFormData = false) => {
	// 测试环境返回模拟数据
	if (isTestEnvironment()) {
		console.log('测试环境请求:', url, method, data);
		return new Promise((resolve) => {
			setTimeout(() => {
				// 根据请求类型返回不同的模拟数据
				if (url === '/auth/login') {
					resolve({
						code: 200,
						message: '登录成功',
						data: {
							token: 'mock_token_for_testing',
							user: {
								id: 1,
								username: 'abc',
								age: 25,
								gender: '男',
								ethnicity: '汉族',
								mandarin_level: '一级甲等',
								role: 'user'
							}
						}
					});
				} else if (url === '/auth/register') {
					resolve({
						code: 200,
						message: '注册成功',
						data: {
							id: 1,
							username: data.username
						}
					});
				} else if (url === '/auth/update') {
					resolve({
						code: 200,
						message: '更新成功',
						data: {
							...data,
							id: 1
						}
					});
				} else if (url === '/auth/password') {
					resolve({
						code: 200,
						message: '密码修改成功',
						data: null
					});
				} else if (url === '/sentences') {
					resolve({
						code: 200,
						message: '获取成功',
						data: [
							{
								id: 1,
								content: "新疆是个好地方"
							},
							{
								id: 2,
								content: "乌鲁木齐是新疆维吾尔自治区的首府"
							},
							{
								id: 3,
								content: "新疆的瓜果非常甜美"
							}
						]
					});
				} else if (url === '/sentences/assigned') {
					resolve({
						code: 200,
						message: '获取成功',
						data: {
							sentences: [
								{
									id: 1,
									content: "天山雪峰在阳光下闪闪发光",
									sequence_order: 1,
									is_completed: true
								},
								{
									id: 2,
									content: "新疆的葡萄又大又甜",
									sequence_order: 2,
									is_completed: true
								},
								{
									id: 3,
									content: "巴扎里的烤羊肉串香气扑鼻",
									sequence_order: 3,
									is_completed: false
								},
								{
									id: 4,
									content: "喀纳斯湖水清澈见底",
									sequence_order: 4,
									is_completed: false
								},
								{
									id: 5,
									content: "维吾尔族的歌舞热情奔放",
									sequence_order: 5,
									is_completed: false
								}
							],
							total: 5,
							completed: 2,
							current_index: 3,
							completion_rate: 40.0
						}
					});
				} else if (url === '/sentences/next') {
					resolve({
						code: 200,
						message: '获取成功',
						data: {
							sentence: {
								id: 3,
								content: "巴扎里的烤羊肉串香气扑鼻",
								sequence_order: 3
							},
							all_completed: false,
							has_assignments: true
						}
					});
				} else if (url === '/sentences/progress') {
					resolve({
						code: 200,
						message: '获取成功',
						data: {
							total: 5,
							completed: 2,
							pending: 3,
							completion_rate: 40.0,
							current_sentence: {
								id: 3,
								content: "巴扎里的烤羊肉串香气扑鼻",
								sequence_order: 3
							}
						}
					});
				} else if (url === '/recordings/user') {
					resolve({
						code: 200,
						message: '获取成功',
						data: [
							{
								id: 1,
								user_id: 1,
								sentence_id: 1,
								sentence_content: "新疆是个好地方",
								audio_file: "/static/demo.mp3",
								created_at: "2023-06-15 12:30:45"
							},
							{
								id: 2,
								user_id: 1,
								sentence_id: 2,
								sentence_content: "乌鲁木齐是新疆维吾尔自治区的首府",
								audio_file: "/static/demo.mp3",
								created_at: "2023-06-15 12:45:30"
							},
							{
								id: 3,
								user_id: 1,
								sentence_id: 3,
								sentence_content: "新疆的瓜果非常甜美",
								audio_file: "/static/demo.mp3",
								created_at: "2023-06-15 13:00:15"
							}
						]
					});
				} else if (url === '/recordings/stats') {
					resolve({
						code: 200,
						message: '获取成功',
						data: {
							completed: 2,
							remaining: 3
						}
					});
				} else if (url.startsWith('/recordings/') && method === 'DELETE') {
					resolve({
						code: 200,
						message: '删除成功',
						data: null
					});
				} else {
					resolve({
						code: 200,
						message: '操作成功',
						data: {}
					});
				}
			}, 500);
		});
	}
	
	// 实际环境请求
	const fullUrl = BASE_URL + url;
	const token = getToken();
	
	// 构建请求头
	const headers = {
		'Content-Type': isFormData ? 'multipart/form-data' : 'application/json'
	};
	
	// 只有在有token的情况下才添加Authorization头
	if (token) {
		headers['Authorization'] = `Bearer ${token}`;
		console.log('使用token:', token);
	}
	
	console.log('发送请求到:', fullUrl);
	console.log('请求方法:', method);
	console.log('请求数据:', data);
	console.log('请求头:', headers);
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: fullUrl,
			method: method,
			data: data,
			header: headers,
			success: (res) => {
				console.log('请求成功, 状态码:', res.statusCode);
				console.log('响应数据:', res.data);
				
				if (res.statusCode === 200) {
					resolve(res.data);
				} else if (res.statusCode === 401) {
					// token过期或无效
					console.error('认证失败, token可能已过期');
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/login'
						});
					}, 1500);
					reject(res.data);
				} else {
					console.error('请求失败, 状态码:', res.statusCode, '错误信息:', res.data);
					uni.showToast({
						title: res.data.message || res.data.msg || '请求失败',
						icon: 'none'
					});
					reject(res.data);
				}
			},
			fail: (err) => {
				console.error('请求错误:', err);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

// 上传文件方法
const uploadFile = (url, filePath, formData = {}) => {
	// 测试环境返回模拟数据
	if (isTestEnvironment()) {
		console.log('测试环境上传文件:', url, filePath, formData);
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve({
					code: 200,
					message: '上传成功',
					data: {
						id: Math.floor(Math.random() * 1000) + 10,
						user_id: 1,
						sentence_id: formData.sentence_id,
						audio_file: "/static/demo.mp3",
						created_at: new Date().toISOString().replace('T', ' ').substring(0, 19)
					}
				});
			}, 1000);
		});
	}
	
	// 实际环境请求
	const fullUrl = BASE_URL + url;
	const token = getToken();
	
	// 构建请求头
	const headers = {};
	
	// 只有在有token的情况下才添加Authorization头
	if (token) {
		headers['Authorization'] = `Bearer ${token}`;
		console.log('上传使用token:', token);
	}
	
	console.log('上传文件到:', fullUrl);
	console.log('文件路径:', filePath);
	console.log('表单数据:', formData);
	console.log('请求头:', headers);
	
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: fullUrl,
			filePath: filePath,
			name: 'audio_file',
			formData: formData,
			header: headers,
			success: (res) => {
				console.log('上传成功, 状态码:', res.statusCode);
				
				if (res.statusCode === 200) {
					try {
						let data = JSON.parse(res.data);
						console.log('解析后的响应数据:', data);
						resolve(data);
					} catch (e) {
						console.error('解析响应数据失败:', e);
						console.log('原始响应数据:', res.data);
						reject(new Error('解析响应数据失败'));
					}
				} else if (res.statusCode === 401) {
					// token过期或无效
					console.error('认证失败, token可能已过期');
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/login'
						});
					}, 1500);
					reject(res);
				} else {
					console.error('上传失败, 状态码:', res.statusCode);
					try {
						let data = JSON.parse(res.data);
						console.log('错误响应数据:', data);
						uni.showToast({
							title: data.message || data.msg || '上传失败',
							icon: 'none'
						});
						reject(data);
					} catch (e) {
						console.error('解析错误响应数据失败:', e);
						console.log('原始错误响应数据:', res.data);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
						reject(new Error('上传失败'));
					}
				}
			},
			fail: (err) => {
				console.error('上传文件错误:', err);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

// 认证相关API
export const authAPI = {
	// 用户注册
	register: (data) => {
		return request('/api/auth/register', 'POST', data);
	},
	
	// 用户登录
	login: (data) => {
		return request('/api/auth/login', 'POST', data);
	},
	
	// 更新用户信息
	updateUserInfo: (data) => {
		return request('/api/auth/update', 'PUT', data);
	},
	
	// 修改密码
	changePassword: (data) => {
		return request('/api/auth/password', 'PUT', data);
	}
};

// 句子相关API
export const sentenceAPI = {
	// 获取句子列表（保留原接口，管理员使用）
	getSentences: () => {
		return request('/api/sentences', 'GET');
	},

	// 搜索句子（保留原接口，管理员使用）
	searchSentences: (keyword) => {
		return request('/api/sentences', 'GET', { search: keyword });
	},

	// 获取用户分配的句子列表
	getAssignedSentences: () => {
		return request('/api/sentences/assigned', 'GET');
	},

	// 获取下一个待录制句子
	getNextSentence: () => {
		return request('/api/sentences/next', 'GET');
	},

	// 获取录制进度
	getProgress: () => {
		return request('/api/sentences/progress', 'GET');
	}
};

// 录音相关API
export const recordingAPI = {
	// 获取用户已完成的录音
	getUserRecordings: () => {
		return request('/api/recordings/user', 'GET');
	},
	
	// 获取用户统计数据（已完成录音数和剩余任务数）
	getUserStats: () => {
		return request('/api/recordings/stats', 'GET');
	},
	
	// 上传录音
	uploadRecording: (sentenceId, filePath) => {
		return uploadFile('/api/recordings', filePath, {
			sentence_id: sentenceId
		});
	},
	
	// 获取录音文件URL
	getRecordingUrl: (recordingId) => {
		if (isTestEnvironment()) {
			return '/static/demo.mp3';
		}
		return `${BASE_URL}/api/recordings/audio/${recordingId}`;
	},
	
	// 删除录音
	deleteRecording: (recordingId) => {
		return request(`/api/recordings/${recordingId}`, 'DELETE');
	}
};

export default {
	authAPI,
	sentenceAPI,
	recordingAPI
}; 